#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Author    :breeze
# @Time      :2019/4/10
# @Email     :wangbaoshan@bbdservice.com
# @File      :IC24_Past3MonsAddedTinyCompLoanCnt
# @Software  :PyCharm


'''eof
name:过去3个月新增小额贷款笔数
code:IC24_Past3MonsAddedTinyCompLoanCnt_2D
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime
import pandas as pd
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def get_date_list():
    try:
        now = datetime.now()
        aaa = [(now + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [-3, 0]]
        return aaa
    except:
        return None


# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date


def past3MonsAddedTinyCompLoanCnt():
    data = IC_DSJ_2D.get('data')
    dateList = get_date_list()
    factor = []
    # 借贷账户信息 PDA[1.1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            for i in PD01:
                # 基本信息段 PD01A[1.1]
                PD01A = getTable(i, 'PD01A', 1, 1)
                if PD01A == [{}]:
                    factor.append(None)
                elif PD01A == 0:
                    factor.append(0)
                else:
                    # 业务管理机构类型
                    PD01AD02 = PD01A[0].get("PD01AD02")
                    # 开立日期
                    PD01AR01 = PD01A[0].get("PD01AR01")
                    PD01AR01 = date_format(PD01AR01)
                    if PD01AD02 not in null_type_list and PD01AR01 not in null_type_list:
                        if PD01AD02 == "51" and dateList[0] < PD01AR01.strftime('%Y%m%d') < dateList[1]:
                            factor.append(1)
                        else:
                            factor.append(0)
                    else:
                        factor.append(None)
    factor = [x for x in factor if x is not None]
    if len(factor) == 0:
        return u'缺失值'
    else:
        return sum(factor)


if __name__ == '__main__':
    file_obj = open(r'../../data/IC/IC24_Past3MonsAddedTinyCompLoanCnt/IC.json', 'r')
    content = file_obj.read()
    IC_DSJ_2D = json.loads(content, strict=False)
    aa = past3MonsAddedTinyCompLoanCnt()
    print aa

result = past3MonsAddedTinyCompLoanCnt()
